from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
from flask_mail import Mail
from flaskext.markdown import Markdown

login_manager = LoginManager()
login_manager.session_protection = "strong"
login_manager.login_view = 'loginview.login'

mail = Mail()
bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()


@login_manager.user_loader
def load_user(userid):
    from .modle import TUser
    return TUser.query.filter_by(user_id=userid).first()


def createapp(config_name):
    app = Flask(__name__, static_url_path="")
    app.config.from_object(config[config_name])

    # 注册蓝本
    from .main import blueprint
    app.register_blueprint(blueprint)
    from .main import loginprint
    app.register_blueprint(loginprint)
    from .main import userprint
    app.register_blueprint(userprint)
    from .main import passageprint
    app.register_blueprint(passageprint)

    # 插件初始化
    bootstrap.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)

    # 旧模式
    markdown = Markdown(app)

    return app
